//ie8 如果不用这种写法会报define undefined
seajs.Module.define(function (require) {
    require("treeview.css");
    require("treeview.js");
    $.fn.selectTree = function (_setting) {
        var $this = $(this);

        function refreshVal() {
            var str = '', append = target.find('[data-append]');
            append.each(function (i) {
                str += $(this).data('append');
                if (append.length - 1 > i) {
                    str += ',';
                }
            });
            $this.val(str);
        }

        function checkNode(data) {
            target.find('.default').hide();
            target.find('.select2-selection__rendered').append('<span data-append="' + data.id + '">' +
                (target.find('[data-append]').length == 0 ? '' : ',' ) + data.text + '</span>');
            refreshVal();
            $this.trigger('checkNode', [data, this]);
        }

        function unCheckNode(data) {
            target.find('[data-append=' + data.id + ']').remove();
            var append = target.find('[data-append]');
            if (append.length == 0) {
                target.find('.default').show();
            }
            var first = append.first();
            if (first.text().substring(0, 1) == ',')
                first.text(first.text().substring(1));
            refreshVal();
            $this.trigger('unCheckNode', [data, this]);
        }

        function defaultData(data, defaultVal) {
            return (function (data, defaultVal) {
                var fun = arguments.callee;
                $.each(data, function () {
                    if (defaultVal.indexOf(',' + this.id + ',') >= 0) {
                        $.extend(true, this, {state: {checked: true}});
                        checkNode(this);
                    }
                    if (!!this.nodes) {
                        this.nodes = fun(this.nodes, defaultVal);
                    }
                });
                return data;
            })(data, ',' + defaultVal + ",");

        }

        var $setting = $.extend(true, {
            treeOptions: {
                levels: 1,
                showCheckbox: true,
                selectedColor: '',
                selectedBackColor: '',
                showBorder: false,
                onNodeChecked: function (event, data) {
                    checkNode.apply(this, [data]);
                },
                onNodeUnchecked: function (event, data) {
                    unCheckNode.apply(this, [data]);
                }
            },
            reorganizeData: function (data) {
                var nodes = [];
                var fun = arguments.callee;
                $.each(data, function () {
                    var node = {
                        text: this.text,
                        level: this.level,
                        id: this.id
                    }
                    if (this.children.length > 0) {
                        node.nodes = fun(this.children);
                    }
                    nodes.push(node);
                });
                return nodes;
            }
        }, _setting);
        var treeView = $('<div class="select-treeView select2"></div>');
        var parent = $(this).parent();
        var id = $(this).attr('id');
        $('body').append(treeView);
        treeView.treeview($setting.treeOptions);
        treeView.hide();
        //初始化treeView的滚动条
        treeView.niceScroll({
            styler: "fb",
            autohidemode: false,
            cursorcolor: "#68bf4a",
            cursorwidth: '6',
            cursorborderradius: '10px',
            background: '#404040',
            spacebarenabled: false,
            cursorborder: ''
        });
        treeView.on('addNode', function (e, item, lv, data) {
            item.attr('data-id', data.id);
        })
        //创建模拟下拉框
        var target = $('<span class="select2 select-treeView-inline select2-container select2-container--default select2-container--below select2-container--focus">' +
            '<span class="selection">' +
            '<span class="select2-selection select2-selection--single">' +
            '<span class="select2-selection__rendered"><span class="default">请点击选择</span></span>' +
            '<span class="select2-selection__arrow"><b role="presentation"></b></span>' +
            '</span>' +
            '</span>' +
            '<span class="dropdown-wrapper" ria-hidden="true"></span>' +
            '</span>');
        target.width(parent.width());
        $(this).hide().after(target);
        //显示下拉项
        var show = function () {
            if (target.is('.select2-container--open')) {
                hide();
                return;
            }
            var offset = target.offset();
            treeView.css({
                width: target.width() - 1,
                left: offset.left,
                top: (offset.top + target.height() - 1)
            });
            target.addClass('select2-container--open');
            treeView.show();
            //全局绑定事件
            $(document.body).on('mousedown.select2.' + id, function (e) {
                var $target = $(e.target);
                var $select = $target.closest('.select2');
                var $all = $('.select2.select2-container--open');
                $all.each(function () {
                    //判断当前事件源如果不是模拟下拉框，和treeView就隐藏
                    if (this == $select[0] || treeView.is($select)) {
                        return;
                    }
                    hide();
                });
            });
        }
        //隐藏下拉项
        var hide = function () {
            target.removeClass('select2-container--open');
            treeView.hide();
            $(document.body).off('mousedown.select2.' + id);
        }
        //点击显示
        target.find('.select2-selection').click(function () {
            show();
        });
        var selectTree = {
            treeView: treeView,
            id: id,
            target: target,
            show: show,
            hide: hide,
            checkNode: checkNode,
            unCheckNode: unCheckNode,
            input: $(this),
            setting: $setting,
            refreshView: function (data) {
                //将已选中文案清空
                target.find('[data-append]').remove();
                target.find('.default').show();
                $this.val('');
                var data = $setting.reorganizeData(data);
                if (!!$this.data('value')) {
                    data = defaultData(data, $this.data('value'));
                    $this.removeAttr('data-value');
                }
                $setting.treeOptions.data = data;
                treeView.treeview($setting.treeOptions);
            }
        };
        $(this).data('selectTree', selectTree);
        return selectTree;
    };
});